package org.example.im.server.handler.impl.biz;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import org.example.im.bean.protocol.CommandType;
import org.example.im.bean.protocol.request.CreateGroupRequestPacket;
import org.example.im.bean.protocol.response.CreateGroupResponsePacket;
import org.example.im.bean.session.Session;
import org.example.im.common.util.SessionUtil;
import org.example.im.common.util.UUIDUtil;
import org.example.im.server.handler.ServerHandler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 创建群
 */
@Component
public class CreateGroupHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> implements ServerHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket request) throws Exception {
        // 待创建组的群成员
        List<String> userIdList = request.getUserIdList();
        // channel分组
        DefaultChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        List<String> userNameList = new ArrayList<>();
        userIdList.forEach(userId -> {
            Channel channel = SessionUtil.getChannel(userId);
            if (Objects.nonNull(channel)) {
                channelGroup.add(channel);
                Session session = SessionUtil.getSession(channel);
                if (Objects.nonNull(session)) userNameList.add(session.getUserName());
            }
        });
        String groupId = UUIDUtil.randomUid();
        CreateGroupResponsePacket response = CreateGroupResponsePacket.builder().success(true).groupId(groupId).userNameList(userNameList).build();
        // 广播群成员
        channelGroup.writeAndFlush(response);
        // 群组信息
        SessionUtil.bindChannelGroup(groupId, channelGroup);
    }

    @Override
    public CommandType genType() {
        return CommandType.CREATE_GROUP_REQUEST;
    }
}
